{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "6f23d4f8-5921-49da-be24-1a6b16fbee95",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "'2.3.3'"
      ]
     },
     "execution_count": 1,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 导入numpy\n",
    "import numpy as np\n",
    "np.__version__"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "d5df6943-d8d3-41c4-afef-a302276af6c2",
   "metadata": {},
   "source": [
    "### numpy与原生python性能对比"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "98806971-1fd4-44ec-9113-ccdf9b54f725",
   "metadata": {},
   "source": [
    "- 求数组x中所有数平方之和"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "id": "650192c2-613a-4394-9e12-ed91c0684034",
   "metadata": {},
   "outputs": [],
   "source": [
    "n = 1000000"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "a525836d-200f-4c18-a575-8b6a71f5307b",
   "metadata": {},
   "source": [
    "#### Python 原生语法实现 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "id": "df6d9e17-22cd-404d-8d83-11c284ad25d6",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "51.2 ms ± 461 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)\n"
     ]
    }
   ],
   "source": [
    "%%timeit\n",
    "x = [i for i in range(n+1)]\n",
    "sum_x = 0\n",
    "for i in x:\n",
    "    sum_x += i**2\n",
    "sum_x"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c0f48c08-ea19-4a5d-9dd5-b7a1123e0145",
   "metadata": {},
   "source": [
    "#### Numpy实现"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "id": "d4735e09-a012-46df-9008-058cc5175275",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1.17 ms ± 92.9 μs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)\n"
     ]
    }
   ],
   "source": [
    "%%timeit\n",
    "x = np.arange(n+1)\n",
    "sum_x = np.sum(x**2)\n",
    "sum_x"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "1816245e-f88b-4aac-a5c3-dfa1fc3848f4",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
